<template>
  <div class="login-container">
    <el-form class="login-form" v-model="loginForm" label-position="top">
      <h2 class="login-title">用户登录</h2>

      <el-form-item label="用户名">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
      </el-form-item>

      <el-button type="primary" class="login-button" @click="login">登录</el-button>
    </el-form>
  </div>
</template>

<script setup>
import api from '@/api'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const loginForm = ref({
  username: '',
  password: ''
})

const login = async () => {
  const { data: res } = await api.login({
    username: loginForm.value.username,
    password: loginForm.value.password
  })
  if (res?.code === 200) {
    if (!res?.data?.token) {
      ElMessage.error('登录失败: 缺少令牌')
      return
    }
    localStorage.setItem('token', res?.data?.token)
    ElMessage.success('登录成功')
    // 可以在这里添加跳转逻辑，比如跳转到首页
    router.push({ name: 'home' })
    return
  }

  ElMessage.error('登录失败: ' + (res?.message || '未知错误'))
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 1.5rem;
}

.login-button {
  width: 100%;
  font-size: 1rem;
}
</style>
